<?php
namespace Api\Controller;
use Think\Controller;

class APIController extends Controller
{
    private $signature = '';
    private $dtype = 'json'; // 默认json数据返回
    protected $Config = [];

    //构造函数
    public function __construct(){
        parent::__construct();
        $this->request_data = $this->_I('', 'request');
        if($this->request_data['dtype']){
            $this->dtype = $this->request_data['dtype'];
        }
    }

    protected function _initialize() {
        $domain_url = ($_SERVER['REQUEST_SCHEME']?:(strpos($_SERVER['SERVER_PROTOCOL'],'HTTPS')?'https':'http')).'://'.$_SERVER['HTTP_HOST'].'/';
        C('DOMAIN_URL',$domain_url);
        $this->Config = C('Config');
    }
    
    /**
     * API输出结果
     * @var array
     */
    public $res_data = array(
        'code_key' => 'success',
        'code' => '',
        'msg' => '',
        'data' => array()
    );

    /**
     * I方法重写
     */
    public function _I($name = '', $method = 'get'){
        if($name){
            return I($method . '.' . $name);
        }else{
            return I($method . '.');
        }
    }



    /**
     * API结果输出
     */
    public function apiReply(){
    	
        if(C('RESULT_CODE.' . $this->res_data['code_key'])){
            $code_configs = C('RESULT_CODE.' . $this->res_data['code_key']);
            $this->res_data['msg'] = $code_configs['msg'];
            $this->res_data['code'] = $code_configs['code'];
        }
        header("Access-Control-Allow-Origin: *");
        ob_clean();
        $this->ajaxReturn($this->res_data, $this->dtype);
    }

    /**
     * 验证接口请求合法性
     */
    public function safeChecked(){
        //return;
        $data = I('param.');
        if(!$data){
            $data = file_get_contents('php://input');
            $data = json_decode($data,true);
            debug($data);
        }
        if(!$this->getSignVeryfy($data, $data['sign'])){
            debug($data);
            $this->res_data['code_key'] = 'lawless';
            $this->res_data['data'] = $this->signature;
            $this->apiReply();
        }
        /*if((time() - $data['timestamps']) > 3){
            $this->res_data['code_key'] = 'lawless';
            $this->res_data['data'] = '签名已过期';
            $this->apiReply();
        }*/
        return true;
    }
    /**
     * 获取收银接口的签名验证结果
     * @param $para_temp 通知返回来的参数数组
     * @param $sign 返回的签名结果
     * @return 签名验证结果
     */
    function getSignVeryfy($para_temp, $sign) {
        //除去待签名参数数组中的签名参数
        /*$para_filter = $this->ParaFilter($para_temp);
        //把数组转成json格式字符串
        $prestr = json_encode($para_filter,JSON_UNESCAPED_UNICODE);*/
        $prestr = $this->filterNonceTimestamps($para_temp);
        $prestr .= '|' . C('API_SAFE_KEY');

        $signature = strtoupper(md5($prestr));

        $this->signature = $signature . ' ## ' . $prestr;
        //$this->signature = $signature;
        return $signature === $sign;
    }
    /**
     * 除去数组中的空值和签名参数
     * @param $para 签名参数组
     * @return array 去掉签名参数后的新签名参数组
     */
    public function ParaFilter($para) {
        $para_filter = array();
        while (list ($key, $val) = each ($para)) {
            if($key == "sign" || $key == "sign_type")continue;
            else    $para_filter[$key] = urlencode($para[$key]);
        }
        return $para_filter;
    }

    public function filterNonceTimestamps($para) {
        $string  = '';
        while (list ($key, $val) = each ($para)) {
            if(in_array($key,['timestamps','nonce'])){
                $string .= $para[$key];
            }
        }
        return $string;
    }

    /*
     * 生成随机数字字符串
     * @param   $length   字符串长度             
     * @return  string
     */

    public function createRandomStr($length = 10){
        $str = '012345678901234567890123456789';
        return substr(str_shuffle($str), 0,$length);
    }

    /**
     * 发送模板消息
     */
    public function sendTemplteMsg($order_num){
        try{
            $obj = D('Order');
            $order = $obj->where(array('order_num' => $order_num))->find();
            $orderinfo = M('order_info')->where(array('order_id' => $order['id']))->find();
            //获取用户openid
            $data = [
                'touser' => M('user')->where(array('id' => $order['user_id']))->getField('openid'),
                'template_id' => 'Uqw4p1myUgPbmU5KR3x8RRtyJEK4habCykfP9Rd-GHQ',
                'form_id' => $order['formId'],
                'data' => [
                    'keyword1' => ['value' => $order['order_num']],
                    'keyword2' => ['value' => $orderinfo['name']],
                    'keyword3' => ['value' => $order['message']?:'无备注']
                ]
            ];
            $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.getAccessToken();
            $result = curl($url,$data,'post','json');
            debug($result);
        }catch(\Excepiton $e){
            debug($e,'notify_log.txt');
        }
    }
}